package com.song.module.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.song.common.constant.Constant;
import com.song.common.util.CharsetKit;
import com.song.common.util.HttpUtils;
import com.song.common.util.StringUtil;
import com.song.module.admin.entity.ApCookbook;
import com.song.module.admin.entity.ApCookbookIngredient;
import com.song.module.admin.entity.ApCookbookInstruction;
import com.song.module.admin.mapper.ApCookbookIngredientMapper;
import com.song.module.admin.mapper.ApCookbookInstructionMapper;
import com.song.module.admin.mapper.ApCookbookMapper;
import com.song.module.admin.service.IFoodService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述
 *
 * @author song
 * @version 1.0
 * @date 2024-02-24 14:36:33
 */
@Service
@AllArgsConstructor
public class FoodServiceImpl implements IFoodService {


    private final ApCookbookMapper apCookbookMapper;

    private final ApCookbookIngredientMapper cookbookIngredientMapper;

    private final ApCookbookInstructionMapper cookbookInstructionMapper;

    @Override
    public void acquire() throws IOException {
        String data = HttpUtils.sendPost("https://www.xiachufang.com/juno/api/v2/search/universal_search_v2.json", "{\"q\":\"家常菜\",\"cursor\":\"NDA=\",\"order_by\":\"\",\"size\":50,\"search_type\":1091,\"sk\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOjE3NjU5MzQ1NywidWlkIjoxNjg3NzkzMzQsImlhdCI6MTcwODc1MjQ3NC4wLCJvIjo1fQ.MSo_63NZ7Ca8iPDESgpQ-2rf0hrJjRLgt3vYDUMmD3U\",\"is_weapp\":1,\"weapp_src\":\"xcf\"}", getHeaders());
        if (StringUtil.isEmpty(data)) {
            return;
        }
        String result = CharsetKit.unicodeToString(data);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String status = jsonObject.getString("status");
        if (Constant.OK.equals(status)) {
            JSONObject content = jsonObject.getJSONObject("content");
            JSONArray objects = content.getJSONArray("content");
            ArrayList<ApCookbook> list = new ArrayList<>();
            for (int i = 0; i < objects.size(); i++) {
                JSONObject object = objects.getJSONObject(i).getJSONObject("content");
                Long id = object.getJSONObject("object").getLong("id");
                String name = object.getJSONObject("object").getString("name");
                String desc = object.getJSONObject("object").getString("desc");
                String photo = object.getJSONObject("object").getString("photo");
                ApCookbook cookbook = ApCookbook.builder().foodId(String.valueOf(id)).description(desc).name(name).picture(photo).thumbUpNumber(0).build();
                list.add(cookbook);
            }
            apCookbookMapper.insertBatchSomeColumn(list);
        }
    }



    @Override
    public void getFoodDetail() throws IOException {
        List<ApCookbook> apCookbooks = apCookbookMapper.selectList(null);
        ArrayList<ApCookbookIngredient> ingredientList = new ArrayList<>();
        ArrayList<ApCookbookInstruction> instructions = new ArrayList<>();
        for (ApCookbook apCookbook : apCookbooks) {
            String data = HttpUtils.sendGet("https://www.xiachufang.com/juno/api/v2/recipes/show_v2.json?id=" + apCookbook.getFoodId() + "&mode=full&sk=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOjE3NjU5MzQ1NywidWlkIjoxNjg3NzkzMzQsImlhdCI6MTcwODc1MjQ3NC4wLCJvIjo1fQ.MSo_63NZ7Ca8iPDESgpQ-2rf0hrJjRLgt3vYDUMmD3U&is_weapp=1&weapp_src=xcf", getHeaders());
            JSONArray ingredient = JSONObject.parseObject(data).getJSONObject("content").getJSONObject("recipe").getJSONArray("ingredient");
            for (int i = 0; i < ingredient.size(); i++) {
                String name = ingredient.getJSONObject(i).getString("name");
                String amount = ingredient.getJSONObject(i).getString("amount");
                ingredientList.add(ApCookbookIngredient.builder().name(name).amount(amount).foodId(apCookbook.getFoodId()).foodName(apCookbook.getName()).build());
            }
            JSONArray instruction = JSONObject.parseObject(data).getJSONObject("content").getJSONObject("recipe").getJSONArray("instruction");
            for (int i = 0; i < instruction.size(); i++) {
                String step = instruction.getJSONObject(i).getString("step");
                String text = instruction.getJSONObject(i).getString("text");
                String url = instruction.getJSONObject(i).getString("url");
                instructions.add(ApCookbookInstruction.builder().step(Integer.parseInt(step)).description(text).foodId(apCookbook.getFoodId()).url(url).foodName(apCookbook.getName()).build());
            }
        }
        cookbookIngredientMapper.insertBatchSomeColumn(ingredientList);
        cookbookInstructionMapper.insertBatchSomeColumn(instructions);
    }


    public static Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Length", "274");
        headers.put("X-Web_XHR", "1");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309092b) XWEB/8555");
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "*/*");
        headers.put("Sec-Fetch-Site", "cross-site");
        headers.put("Sec-Fetch-Mode", "cors");
        headers.put("Sec-Fetch-Dest", "empty");
        headers.put("Referer", "https://servicewechat.com/wxb11f14b08a38ba44/116/page-frame.html");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        return headers;
    }
}
